<template>
  <ContentWrap>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <div
        class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
      >
        <span>代理商信息 </span>
      </div>

      <el-form-item label="代理商名称" prop="agentName">
        <el-input v-model="formData.agentName" class="w-120!" placeholder="请输入代理名称" />
      </el-form-item>
      <el-form-item label="代理商等级" prop="agentLevelId">
        <AgentLevelSelect :classStyle="'w-120!'" v-model="formData.agentLevelId" />
      </el-form-item>
      <el-form-item label="关联用户" prop="agentUserName">
        <div class="flex">
          <el-input
            disabled
            v-model="formData.agentUserName"
            class="w-120!"
            placeholder="暂无关联用户"
          />
          <el-button type="primary" @click="openMemberUserSelect" class="ml-10px"
            >选择用户</el-button
          >
        </div>
      </el-form-item>
      <el-form-item label="上级代理">
        <div class="flex">
          <el-input
            disabled
            v-model="formData.agentParentName"
            class="w-120!"
            placeholder="顶级代理"
          />
          <el-button type="primary" class="ml-10px" @click="openUpdateBindUserForm"
            >选择代理</el-button
          >
        </div>
      </el-form-item>
    </el-form>
    <el-form-item>
      <div class="flex justify-center w-full">
        <el-button :loading="formLoading" type="primary" @click="submitForm"> 保存 </el-button>
        <el-button @click="close">返回</el-button>
      </div>
    </el-form-item>
    <!-- 修改上级推广人表单 -->
    <DistributorUserSelect ref="updateBindUserFormRef" @success="setDistributor" />
    <!-- 选择关联会员 -->
    <MemberUserSelect ref="memberUserSelectRef" @success="setMemberUser" />
  </ContentWrap>
</template>
<script setup lang="ts">
import { useTagsViewStore } from '@/store/modules/tagsView'

import * as AgentUserApi from '@/api/mall/trade/agent/user'

const { push, currentRoute } = useRouter() // 路由
const { params } = useRoute() // 查询参数
const { delView } = useTagsViewStore() // 视图操作
import AgentLevelSelect from '@/views/mall/trade/agent/level/components/AgentLevelSelect.vue'
import MemberUserSelect from '@/views/member/user/components/MemberUserSelect.vue'
import DistributorUserSelect from './../DistributorUserSelect.vue'
/** 会员等级表单 **/
defineOptions({ name: 'BrokerageLevelForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref<AgentUserApi.AgentUserVO>({
  agentLevelId: undefined,
  agentName: undefined,
  agentUserId: undefined,
  agentUserName: undefined,

  agentParentId: undefined,
  agentParentName: undefined,
  agentId: undefined as any
})
const formRules = reactive({
  agentLevelId: [{ required: true, message: '等级不能为空', trigger: ['blur', 'change'] }],
  agentName: [{ required: true, message: '代理商名称不能为空', trigger: 'blur' }],

  agentUserName: [{ required: true, message: '关联会员不能为空', trigger: 'blur' }]
})

const formRef = ref() // 表单 Ref
/** 打开表单：修改上级推广人 */
const updateBindUserFormRef = ref()
const openUpdateBindUserForm = (row: any) => {
  updateBindUserFormRef.value.open(row)
}
const setMemberUser = (row) => {
  ;(formData.value.agentUserName = row.nickname), (formData.value.agentUserId = row.id)
}
/** 选择关联会员 */
const memberUserSelectRef = ref()
const openMemberUserSelect = (row: any) => {
  memberUserSelectRef.value.open(row)
}
const setDistributor = (row) => {
  ;(formData.value.agentParentName = row.agentName), (formData.value.agentParentId = row.agentId)
}
/** 打开弹窗 */
const getDetail = async () => {
  const id = params.id as unknown as number
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AgentUserApi.getBrokerageUser(id)
    } finally {
      formLoading.value = false
    }
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    delete formData.value.agentParentName
    delete formData.value.agentUserName

    const data = formData.value as unknown as AgentUserApi.AgentUserVO
    const id = params.id as unknown as number

    if (!id) {
      await AgentUserApi.createBrokerageUser(data)
      message.success(t('common.createSuccess'))
    } else {
      await AgentUserApi.updateBrokerageUser(data)
      message.success(t('common.updateSuccess'))
    }
    // 发送操作成功的事件
    close()
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formRef.value?.resetFields()
}
/** 关闭按钮 */
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'DistributorUser' })
}
/** 初始化 */
onMounted(async () => {
  await getDetail()
})
</script>
